package service

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/wonderivan/logger"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"time"
)

var Configmap configmap

type configmap struct{}

type ConfigMapResp struct {
	Items []corev1.ConfigMap `json:"items"`
	Total int                `json:"total"`
}

func (cm *configmap) GetConfigMaps(namespace, filtername string, limit, page int) (configmapresp *ConfigMapResp, err error) {
	configmapList, err := K8s.ClientSet.CoreV1().ConfigMaps(namespace).List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		logger.Error(errors.New("获取configmap列表失败, " + err.Error()))
		return nil, errors.New("获取configmap列表失败, " + err.Error())
	}
	selectableData := &dataSelector{
		GenericDataList: cm.toCells(configmapList.Items),
		DataSelect: &DataSelectQuery{
			Filter: &FilterQuery{Name: filtername},
			Paginate: &PaginateQuery{
				Limit: limit,
				Page:  page,
			},
		},
	}
	filtered := selectableData.Filter()
	total := len(filtered.GenericDataList)
	data := filtered.Sort().Paginate()

	configmaps := cm.fromCells(data.GenericDataList)

	return &ConfigMapResp{
		Items: configmaps,
		Total: total,
	}, nil
}

func (cm *configmap) GetConfigMapDetail(namespace, configmapname string) (dataList *corev1.ConfigMap, err error) {
	dataList, err = K8s.ClientSet.CoreV1().ConfigMaps(namespace).Get(context.TODO(), configmapname, metav1.GetOptions{})
	if err != nil {
		logger.Error(errors.New("获取configmap失败," + err.Error()))
		return nil, errors.New("获取configmap失败," + err.Error())
	}
	return dataList, nil
}

func (cm *configmap) DeleteConfigMap(namespace, configmapname string) (err error) {
	err = K8s.ClientSet.CoreV1().ConfigMaps(namespace).Delete(context.TODO(), configmapname, metav1.DeleteOptions{})
	if err != nil {
		logger.Error(errors.New("删除configmap失败," + err.Error()))
		return errors.New("删除configmap失败," + err.Error())
	}
	return nil
}

func (cm *configmap) UpdateConfigMap(namespace, content string) (err error) {
	var configmap = &corev1.ConfigMap{}
	err = json.Unmarshal([]byte(content), configmap)
	if err != nil {
		logger.Error(errors.New("反序列化失败," + err.Error()))
		return errors.New("反序列化失败," + err.Error())
	}
	_, err = K8s.ClientSet.CoreV1().ConfigMaps(namespace).Update(context.TODO(), configmap, metav1.UpdateOptions{})
	if err != nil {
		logger.Error(errors.New("更新configmap失败," + err.Error()))
		return errors.New("更新configmap失败," + err.Error())
	}
	return nil
}

type configmapCell corev1.ConfigMap

func (cm configmapCell) GetName() string {
	return cm.GetName()
}
func (cm configmapCell) GetCreation() time.Time {
	return cm.CreationTimestamp.Time
}

func (cm *configmap) toCells(std []corev1.ConfigMap) []DataCell {
	cells := make([]DataCell, len(std))
	for i := range std {
		cells[i] = configmapCell(std[i])
	}
	return cells
}

func (cm *configmap) fromCells(cells []DataCell) []corev1.ConfigMap {
	configmaps := make([]corev1.ConfigMap, len(cells))
	for i := range cells {
		configmaps[i] = corev1.ConfigMap(cells[i].(configmapCell))
	}
	return configmaps
}
